package cat.music.ut.ui.activity

import android.webkit.WebChromeClient
import android.webkit.WebResourceError
import android.webkit.WebResourceRequest
import android.webkit.WebSettings
import android.webkit.WebView
import android.webkit.WebViewClient
import cat.music.ut.base.BaseActivity
import cat.music.ut.component.click
import cat.music.ut.databinding.ActivityWelcomeAdBinding
import cat.music.ut.ui.fragment.openLinkInBrowser

class WelcomeADActivity : BaseActivity<ActivityWelcomeAdBinding>() {
    override val viewBinding: ActivityWelcomeAdBinding
        get() = ActivityWelcomeAdBinding.inflate(layoutInflater)

    override fun initView() {
        setTranslucentStatus()
        vb.ivClose.click {
            finish()
        }
// 启用常用 WebView 设置
        val settings = vb.web.settings
        settings.javaScriptEnabled = true
        settings.domStorageEnabled = true
        settings.allowFileAccess = true
        settings.javaScriptCanOpenWindowsAutomatically = true
        settings.cacheMode = WebSettings.LOAD_DEFAULT
        settings.useWideViewPort = true
        settings.setSupportZoom(true)
        settings.loadWithOverviewMode = true
//        settings.setAppCacheEnabled(true)
        settings.mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW // 兼容 HTTP + HTTPS 内容

        // 启用 WebView 调试（开发时用）
//        vb.web.setWebContentsDebuggingEnabled(true)

        // 防止外部浏览器打开链接
        vb.web.webViewClient = object : WebViewClient() {

            // 新版本 Android 使用此方法处理错误
            override fun onReceivedError(
                view: WebView,
                request: WebResourceRequest,
                error: WebResourceError
            ) {
                // 仅主页面出错才处理，避免每个资源出错都触发
                if (request.isForMainFrame) {
                    view.loadUrl("file:///android_asset/error.html")
                }
            }

            // 旧版兼容处理（API < 23）
            override fun onReceivedError(
                view: WebView,
                errorCode: Int,
                description: String?,
                failingUrl: String?
            ) {
                view.loadUrl("file:///android_asset/error.html")
            }
        }

        // 支持 alert/confirm 等弹窗
        vb.web.webChromeClient = WebChromeClient()
        vb.tvAd.click {
            openLinkInBrowser(this,"http://47.94.210.190:8203/ad/250502/url.html")
        }
        vb.web.loadUrl("http://47.94.210.190:8203/ad/250502/")
        vb.tvMore.click {
            openLinkInBrowser(this,"https://gantanhao.vip/webapp/weixiaodian/index.html?shop_id=380995")
        }
    }

    // 返回键处理（回退网页）
    override fun onBackPressed() {
        if (vb.web.canGoBack()) {
            vb.web.goBack()
        } else {
            super.onBackPressed()
        }
    }

    override fun onDestroy() {
        vb.web.destroy()
        super.onDestroy()
    }
}